import os
import sys
PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../"))
sys.path.insert(0, PROJECT_ROOT)
from datetime import datetime

from src.database.dao.upload_file_dao import UploadedFileDAO

# 添加项目根目录到Python路径
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..')))

from src.database.dao.audio_upload_dao import AudioUploadDAO
from src.utils.logger import log_info, log_error

def migrate_audio_uploads():
    """将AudioUpload表中的数据迁移到UploadedFile表"""
    log_info("开始迁移AudioUpload数据...")
    
    # 获取所有AudioUpload记录
    audio_dao = AudioUploadDAO()
    new_dao = UploadedFileDAO()
    
    try:
        # 使用分页获取所有记录
        page = 1
        page_size = 50
        total_migrated = 0
        total_failed = 0
        
        while True:
            result = audio_dao.get_audio_history(page=page, page_size=page_size)
            if not result.get("success", False):
                log_error(f"获取音频记录失败: {result.get('message', '')}")
                break
                
            records = result.get("data", {}).get("records", [])
            if not records:
                # 没有更多记录了
                break
                
            log_info(f"正在处理第{page}页，共{len(records)}条记录...")
            
            for record in records:
                try:
                    # 准备元数据
                    meta_data = record.get('meta_data', {}) or {}
                    meta_data['group_id'] = record.get('group_id')
                    meta_data['order'] = record.get('order')
                    if record.get('subtitle_path'):
                        meta_data['subtitle_path'] = record.get('subtitle_path')
                    
                    # 创建UploadedFile记录
                    new_dao.create(
                        file_path=record.get('audio_path'),
                        filename=record.get('filename'),
                        file_type='audio',
                        meta_data=meta_data,
                        status=record.get('status', 'active')
                    )
                    
                    total_migrated += 1
                except Exception as e:
                    log_error(f"迁移记录ID={record.get('id')}失败: {e}")
                    total_failed += 1
            
            page += 1
        
        log_info(f"迁移完成！成功迁移: {total_migrated} 条记录, 失败: {total_failed} 条")
        return {"success": True, "migrated": total_migrated, "failed": total_failed}
    
    except Exception as e:
        log_error(f"迁移过程中出错: {e}")
        return {"success": False, "message": str(e)}

if __name__ == "__main__":
    migrate_audio_uploads()